import json

from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer

CONN_LIST = []


class ChatConsumer(WebsocketConsumer):
    def websocket_connect(self, message):
        print("正在连接...")
        self.accept()
        CONN_LIST.append(self)

    def websocket_receive(self, message):
        print('服务器收到数据：', message)
        data = message['text']
        for i in CONN_LIST:
            print(data)
            i.send(data)


    def websocket_disconnect(self, message):
        CONN_LIST.remove(self)
        raise StopConsumer()

